package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.entity.LoginUser;
import org.example.entity.User;
import org.example.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    //查询登录的用户信息是否存在
    @Override
    public UserDetails loadUserByUsername(String username) {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(wrapper);
        //如果没有查询到用户信息
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

        //根据用户信息查询到权限信息存入到LoginUser中,根据用户名查询对应的权限信息然后返回
        //封装成UserDetails对象返回
        return new LoginUser(user.getCommonUserInfo(),user.getLoginInfo());
    }
}